﻿using AngleSharp;
using AngleSharp.Html.Parser;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using GWB.Application.Service.Startup;
using GWB.Core.Common;
using GWB.Core.Model;
using Microsoft.Extensions.FileSystemGlobbing.Internal;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static GWB.Core.Common.DingDingHelper;

namespace GWB.Application.Service.PlatForm.IBK
{
    public class IBKServer : IIBKServer, ITransient, IDynamicApiController
    {
      

        /// <summary>
        /// i爱泊客 启动
        /// </summary>
        /// <returns></returns>
        public void IbkStartup(string carNo)
        {

            var url = "http://mops.fujica.com.cn/v3/Bussiness/GetParkInfo?carNo="+ carNo;
            url = "http://106.12.108.233:8080/";
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("User-Agent", "PostmanRuntime-ApipostRuntime/1.1.0");
            dic.Add("Cache-Control", "no-cache");
            dic.Add("Accept", "*/*");
            dic.Add("Accept-Encoding", "gzip, deflate, br");
            dic.Add("Connection", "keep-alive");
            dic.Add("Cookie", "acw_tc=2f6a1fee17022228296143618e45789a2db35dca662503fb0b729d71e6db17;key=kf463cOCOnr8zttLQ2z0jQ==;acw_tc=2f6a1fcd17016538368182593ec4d7d05cf9818218fb2d02d7f9d3a936a331; 66_sid=anbo_445100202308020312; key=kf463cOCOnr8zttLQ2z0jQ==; OperationCode=vng1gx6PntpB8zt+6d2BLYKx7kOT2aQsG3MvY4/Iv+gfPTVye+NtSw==; WxLoginInfo=0pj6j5u7Fi2YVK5y+xfNPTrQCkzy0aLQcIKIyoxH7lU8wr0e+WLlGyx60FqmdnuObsu0QA00E0LmtoBzsHPcqkyoBtU0+CfX+/BpjiqoOInZibmr/k5ftxqYOmKiUFNO7e3Owj068oGEhyPOjjlv7hV6ItYSrnkqlUwUcLDgOVk1YvPhRZY4rqDCOXjE6Srs6jdv+bB78+3C/W8soasZPw==; WapPay_User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Gpenrq4EyIQF40WR7phk4zPaQOlNh0PY8QEzBfp9oWtIm+Olajzm0EThRjyWR1J6vGzckXQyyacEoKNgzeXNuLR2B/KET4kIxyeOOkUZ++ugmicEVlA+pTQyXUFORLlZti0JcWL03n9M6P03NNGW5Xi3mY7ACxkkjAnIk1mp5boHeuitq0ISUeKUTxPqC9PRNS4oXiXeV8oiA5tZ4FyIAR1MmgXjzbaXK+fI6RDNHbNWOHmbJ72HwYSrNj0WNqNj5iX1qwexdgnOVIKQuGn5hbXpX9UyhvaGLygFvgntyBdWeujOanibePE4VrKfP4HFacekUOMYn1vfXCIZegtrsWoBQ2izkdPbiLeQyGYtYH+FRJyIxMCSzbfUiv86GbnE2DpzWdTd54Ml9wgEEMT/itZC8TZlIyqKkTjili29tBJ1jokaRyPRDuWojLZiZi2S/cBMe0axgItxQqRHUxnZ7dEGDifVjA7DnAz7rlNv3wJnuwZfC1WFwwauK+hw47ND6QsCxov97x3Idn9XRSJs+yOympZrobrVDyZsGzZFSyt/UHkJaOQHzRyW1PMHs4VZ2nckIj16K1dDZRxtV45sHqAPQPlpBokTWYkUUy/QNigyQ60krdmb/qNszgrT47DonBwzGvTEITCq3bncoHycqOpm1L3Z4YTxVb/7klvIQBppaY5zSHJPAbuQPoqwTIYrthrDTey2iveYaemh6CS9xUuNWG8GAcmGzS931hFVtopL7DMI8NIB6qwshMIpWUoFhhniSmfQpGgMAaViW6jKB6qK1d/Chlhxp2D1ZC7vKeifqdsgC3ObG0TOl5TiPHVwsReUAWRYO0e3m+eRlS1Wz40T8dvkUK7qPwWCc1R2V5skx+CLEBdT6epFlYupfwmVyHWBcaqnBJ9mTpUzynXRhsLoPFewDpHUuvcnah4HDzD7XLZ8zQFp/SPNb0mR0kylVL12sfayBZaumP5A==");
            
            var result = "";

            //查询当前车牌号
            var redisStr = RedisHelper.Read(carNo, 1);
            var thiscarNoInfo = string.IsNullOrEmpty(redisStr)?null:JsonConvert.DeserializeObject<ResultEntity>(redisStr);



            var count1 = 0;
            #region http请求
            try
            {
                result = HttpHelper.HttpGet(url, "", dic, "爱泊客", "application/x-www-form-urlencoded; charset=UTF-8");
            }
            catch (Exception e)
            {
                SqlSugarHelper.Db.Insertable(new ErrorLogEntity()
                {
                    CreateTime = DateTime.Now,
                    Module=@$"车牌号:{carNo}_次数:{count1}_模块:http请求",
                    ErrorStr=e.Message,
                }).ExecuteCommandAsync();
                if (count1 >= 3) return;
                result = HttpHelper.HttpGet(url, "", dic, "application/json");
                count1++;
            }
            #endregion

            var html = "";
            var count2 = 0;
            #region html解析

            try
            {
                html = HtmlAnalysis(result);
                if (html == "-1")
                {
                    RedisHelper.Del(carNo,1);
                    return;
                }
            }
            catch (Exception e)
            {
                SqlSugarHelper.Db.Insertable(new ErrorLogEntity()
                {
                    CreateTime = DateTime.Now,
                    Module = @$"车牌号:{carNo}_次数:{count2}_模块:html解析",
                    ErrorStr = e.Message,
                }).ExecuteCommandAsync();
                if (count2 >= 3) return;
                html=HtmlAnalysis(result);
                if (html == "-1")
                {
                    RedisHelper.Del(carNo);
                    return;
                }
                count2++;
            }

            #endregion

            var resData = new ValueEntity();
            var count3 = 0;
            #region 字符串转OBJ

            try
            {
                resData = StrToObj(html);
               
            }
            catch (Exception e)
            {
                SqlSugarHelper.Db.Insertable(new ErrorLogEntity()
                {
                    CreateTime = DateTime.Now,
                    Module = @$"车牌号:{carNo}_次数:{count3}_模块:字符串转OBJ",
                    ErrorStr = e.Message,
                }).ExecuteCommandAsync();
                if (count3 >= 3) return;
                resData = StrToObj(html);
                count3++;
            }

            #endregion

            #region  发送消息

            try
            {
               
                if (thiscarNoInfo==null)
                {
                  var chatSend =  DingDingHelper.ChatSend(new DingDingHelper.Markdown()
                    {
                        title = resData.CarNo,
                        text = @$"#### 车牌号：{resData.CarNo}
#### 停车场：{resData.ParkingName}
#### 入场时间：{resData.BeginTime}
#### 停车时长：-    
#### 查询时间：{DateTime.Now.ToString()}
#### 停车场详细地址：-     
#### 平台：- ",
                    });
                    if (chatSend.errmsg!="ok")
                    {
                        SqlSugarHelper.Db.Insertable(new ErrorLogEntity()
                        {
                            CreateTime = DateTime.Now,
                            Module = @$"车牌号:{carNo}_模块:发送消息",
                            ErrorStr = "消息发送错误",
                        }).ExecuteCommandAsync();
                    }
                }
                //写数据库
                Dictionary<string, string> write = new Dictionary<string, string>();
                write.Add(carNo, JsonConvert.SerializeObject(resData));
                RedisHelper.Write(write, 1);
            }
            catch (Exception e)
            {
                SqlSugarHelper.Db.Insertable(new ErrorLogEntity()
                {
                    CreateTime = DateTime.Now,
                    Module = @$"车牌号:{carNo}_次数:{count1}_模块:发送消息",
                    ErrorStr = e.Message,
                }).ExecuteCommandAsync();
            }
          
            #endregion
           
        }

        /// <summary>
        /// Html解析
        /// </summary>
        /// <returns></returns>
        public string HtmlAnalysis(string html)
        {

            var result = "";
            if (html.IndexOf("strData") == -1)
            {
                return "-1";
            }

            try
            {
                // 正则表达式模式
                string pattern = @"<script>(.*?)</script>";
                // 创建正则表达式对象
                Regex regex = new Regex(pattern, RegexOptions.Singleline);
                // 查找匹配的结果
                MatchCollection matches = regex.Matches(html);
                result = matches[0].Value;


                pattern = @"HasInvoice(.*?)SpecialCar";
                // 创建正则表达式对象
                regex = new Regex(pattern, RegexOptions.Singleline);
                // 查找匹配的结果
                matches = regex.Matches(result);
                result = matches[0].Value;


                //pattern = @"HasInvoice(.*?)}'.";
                //// 创建正则表达式对象
                //regex = new Regex(pattern, RegexOptions.Singleline);
                //// 查找匹配的结果
                //matches = regex.Matches(result);
                //result = matches[0].Value;

                result = result.Replace("&quot;", "");
                result = result.Replace("}'.", "");
            }
            catch (Exception e)
            {
                throw new Exception("HtmlAnalysis_HTML解析错误");
            }


            return result;
        }

        /// <summary>
        /// 字符串转obj
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public ValueEntity StrToObj(string str)
        {
            var result = new ValueEntity();
            try
            {
                var pattern = @"ParkingName:(.*?),ImageUrl";
                // 创建正则表达式对象
                var regex = new Regex(pattern, RegexOptions.Singleline);
                // 查找匹配的结果
                var matches = regex.Matches(str);
                var resultStr = matches[0].Value;
                result.ParkingName = resultStr.Replace("ParkingName:", "").Replace(",ImageUrl", "");




                pattern = @"BeginTime:(.*?),ChargeableTime";
                //创建正则表达式对象
                regex = new Regex(pattern, RegexOptions.Singleline);
                //查找匹配的结果
                matches = regex.Matches(str);
                resultStr = matches[0].Value;

                result.BeginTime = resultStr.Replace("BeginTime:", "").Replace(",ChargeableTime", "");
              

                pattern = @"CarNo:(.*?),ParkingName";
                //创建正则表达式对象
                regex = new Regex(pattern, RegexOptions.Singleline);
                //查找匹配的结果
                matches = regex.Matches(str);
                resultStr = matches[0].Value;
                result.CarNo =resultStr.Replace("CarNo:", "").Replace(",ParkingName", "");
                result.QueryTime = DateTime.Now.ToString();

            }
            catch (Exception e)
            {
                throw new Exception("StrToObj_字符串解析错误");
            }

            return result;
        }

       
        public class ValueEntity
        {
            /// <summary>
            /// 车牌
            /// </summary>
            public string CarNo { get; set; }

            /// <summary>
            /// 查询时间
            /// </summary>
            public string QueryTime { get; set; }

            /// <summary>
            /// 停车场名称
            /// </summary>
            public string ParkingName { get; set; }

            /// <summary>
            /// 开始时间
            /// </summary>
            public string BeginTime { get; set; }
        }
    }
}
